import React from "react";
import { Form, Input, Select, Button, message } from "antd"; // 新增message用于提示
import { useNavigate } from "react-router-dom";
import { addArticle } from "../../../api/articles";

const { Option } = Select;

interface AddArticleFormValues {
  title: string;
  category: string;
  tags: string;
  content: string;
}

const AddArticle: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const onFinish = async (values: AddArticleFormValues) => {
    try {
      const userId = localStorage.getItem('userId');
      if (!userId) {
        message.error('用户未登录，请重新登录');
        return;
      }
      await addArticle({ ...values, userId }); // 携带userId参数
      navigate('/blog/articles');
    } catch (error) {
      console.error('提交文章失败:', error);
    }
  };

  return (
    <div>
      <h2>新增文章</h2>
      <Form
        form={form}
        name="addArticle"
        layout="vertical"
        onFinish={onFinish}
        style={{ maxWidth: 600 }}
      >
        <Form.Item
          name="title"
          label="标题"
          rules={[{ required: true, message: '请输入文章标题' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          name="category"
          label="分类"
          rules={[{ required: true, message: '请选择文章分类' }]}
        >
          <Select placeholder="请选择分类">
            <Option value="技术">技术</Option>
            <Option value="生活">生活</Option>
            <Option value="杂谈">杂谈</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="tags"
          label="标签"
          rules={[{ required: true, message: '请输入文章标签（用逗号分隔）' }]}
        >
          <Input placeholder="示例：React,前端" />
        </Form.Item>

        <Form.Item
          name="content"
          label="内容"
          rules={[{ required: true, message: '请输入文章内容' }]}
        >
          <Input.TextArea rows={6} />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            提交文章
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={() => navigate(-1)}>
            返回列表
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default AddArticle;